package com.tanhua.dubbo.api;


import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


/**
 * @Classname VideoApiImpl
 * @Description TODO
 * @Date 2021/3/15 15:42
 * @Created by gan
 */
@Service
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdService idService;

    //条件小视频
    @Override
    public void save(Video video) {
        video.setId(ObjectId.get());
        video.setCreated(System.currentTimeMillis());
        video.setVid(idService.nextId("video"));
        mongoTemplate.save(video);
    }


    //视频列表，分页查询
    @Override
    public PageResult findPage(Long page, Long pagesize) {
        //构建分页结果
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);

        Query query = new Query();

        // 统计总数
        long count = mongoTemplate.count(query, Video.class);
        pageResult.setCounts(count);
        // 查询分页结果集
       query.with(PageRequest.of(page.intValue()-1,pagesize.intValue()))
               .with(Sort.by(Sort.Order.desc("created")));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        pageResult.setItems(videoList);
        return pageResult;
    }


    //关注视频，作者
    @Override
    public void followUser(FollowUser followUser) {
        //补全
        followUser.setId(ObjectId.get());
        followUser.setCreated(System.currentTimeMillis());
        //关注，保存
        mongoTemplate.save(followUser);


    }


    //取消关注
    @Override
    public void unfollowUser(FollowUser followUser) {
        //构造条件
        Query query=new Query();
        query.addCriteria(Criteria.where("userId").is(followUser.getUserId())
        .and("followUserId").is(followUser.getFollowUserId()));
        //取消关注
        mongoTemplate.remove(query,FollowUser.class);
    }
}
